<template>
  <div class="ml-2 flex-1">
    <a-card :bordered="false" style="height: 820px; width: 1380px">
      <a-form :model="searchForm" ref="formRef" layout="inline">
        <a-form-item label="收费期" name="year">
          <a-date-picker v-model:value="searchForm.year" picker="year" style="width: 120px" />
        </a-form-item>
        <a-form-item label="收费状态" name="chargingStatus">
          <a-select v-model:value="searchForm.chargingStatus" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="供热状态" name="heatingStatus">
          <a-select v-model:value="searchForm.heatingStatus" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="欠费金额范围" name="arrearsAmount">
          <div class="flex items-center">
            <a-input-number v-model:value="searchForm.arrearageBegin" style="width: 120px" placeholder="请输入" />
            <span class="ml-2 mr-2">-</span>
            <a-input-number v-model:value="searchForm.arrearageEnd" style="width: 120px" placeholder="请输入" />
          </div>
        </a-form-item>
        <a-form-item label="阀门类型" name="valveType">
          <a-select v-model:value="searchForm.valveType" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="缴费状态" name="payFeeStatus">
          <a-select v-model:value="searchForm.payFeeStatus" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">
            <SearchOutlined />查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onModal(1)">
            <CheckSquareOutlined />按选择推送
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onModal(2)">
            <MonitorOutlined />按查询条件推送
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary">
            <HistoryOutlined />导出历史
          </a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" row-key="areaID" :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }" :scroll="{ x: 1000, y: 500 }" class="mt-3" />
    </a-card>
    <a-modal :visible="visible" title="推送" width="500px" @cancel="visible = false" @ok="onSubmit">
      <div class="flex items-center">
        <a-form :model="searchForm">
          <a-form-item label="所属项目">
            <a-tree-select v-model:value="searchForm.comId" tree-node-filter-prop="label" style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="comanyList"
              placeholder="请选择所属项目" />
          </a-form-item>
          <a-form-item label="模版类型">
            <a-select v-model:value="searchForm.templateType" style="width: 260px" placeholder="请选择"
              :options="pushOption" @change="getTemplate" />
          </a-form-item>
          <a-form-item label="模版名称">
            <a-select v-model:value="searchForm.templateId" style="width: 260px" placeholder="请选择"
              :options="templateName" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import {
  SearchOutlined,
  CheckSquareOutlined,
  MonitorOutlined,
  HistoryOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {
  getUrgePaymentApi,
  getSelectedPaymentApi,
  getConditionPaymentApi,
  getSubCompanyApi,
  getTelmplateName,
} from '#/api/core/charge';
import { getCompanyTree } from '#/api/core/develop';
import dayjs from 'dayjs';

const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const pushOption = [
  {
    label: '普通短信',
    value: '普通短信',
  },
  {
    label: '催费短信',
    value: '催费短信',
  },
  {
    label: '公众号短信',
    value: '公众号短信',
  },
];
const templateName = ref([]);
interface TreeNode {
  value: string;
  id: string;
  level: string;
  label: string;
  children?: TreeNode[];
}
const selectedRowKeys = ref<any[]>([]);
const modalType = ref(0);
const companyOptions = ref<TreeNode[]>([]);
const searchForm = reactive({
  year: '',
  chargingStatus: undefined,
  heatingStatus: undefined,
  arrearageBegin: '',
  arrearageEnd: '',
  valveType: undefined,
  payFeeStatus: undefined,
  comId: undefined,
  templateType: undefined,
  templateId: undefined,
  applicantId: undefined,
});
const visible = ref(false);
const formRef = ref();
const columns = [
  {
    title: '项目',
    dataIndex: 'comName',
    key: 'comName',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
  },
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
  },
  {
    title: '用户名称',
    dataIndex: 'holder',
    key: 'holder',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
  },
  {
    title: '联系电话',
    dataIndex: 'holdPhone',
    key: 'holdPhone',
  },
  {
    title: '阀门类型',
    dataIndex: 'valveType',
    key: 'valveType',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price',
  },
  {
    title: '应收金额',
    dataIndex: 'receivableTotal',
    key: 'receivableTotal',
  },
  {
    title: '违约金',
    dataIndex: 'arrearageLateFee',
    key: 'arrearageLateFee',
  },
  {
    title: '已收金额',
    dataIndex: 'yjTotal',
    key: 'yjTotal',
  },
  {
    title: '拖欠金额',
    dataIndex: 'arrearageTotal',
    key: 'arrearageTotal',
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else {
    const query = {
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
      headerMessage: {
        year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
        chargingStatus: searchForm.chargingStatus ?? '',
        heatingStatus: searchForm.heatingStatus ?? '',
        arrearageBegin: searchForm.arrearageBegin ?? '',
        arrearageEnd: searchForm.arrearageEnd ?? '',
        valveType: searchForm.valveType ?? '',
        payFeeStatus: searchForm.payFeeStatus ?? '',
      },
    };
    getUrgePaymentApi(query).then((res: any) => {
      dataSource.value = res.data.data.data;
      pagination.total = res.data.data.total;
    });
  }

};
const onModal = (type: number) => {
  modalType.value = type;
  visible.value = true;
};
const onSubmit = () => {
  if (modalType.value === 1) {
    const query = {
      areaIDs: selectedRowKeys.value,
      templateId: searchForm.templateId,
    };
    getSelectedPaymentApi(query).then((res: any) => {
      if (res.data.code === 200) {
        message.success(res.data.data);
      } else {
        message.error('发送失败');
      }
    });
  } else if (modalType.value === 2) {
    const query = {
      headerMessage: {
        year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
        chargingStatus: searchForm.chargingStatus ?? '',
        heatingStatus: searchForm.heatingStatus ?? '',
        arrearageBegin: searchForm.arrearageBegin ?? '',
        arrearageEnd: searchForm.arrearageEnd ?? '',
        valveType: searchForm.valveType ?? '',
        payFeeStatus: searchForm.payFeeStatus ?? '',
      },
      treeData: props.selectedNodeId,
      templateId: searchForm.templateId,
    };
    getConditionPaymentApi(query).then((res: any) => {
      if (res.data.code === 200) {
        message.success(res.data.data);
      } else {
        message.error('发送失败');
      }
    });
  }
};
const comanyList = ref<TreeNode[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): TreeNode[] => {
      console.log(tree);
      return tree.map((item: any): TreeNode => {
        const processedItem: TreeNode = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const getTemplate = (value: any) => {
  console.log(value);
  getTelmplateName(searchForm.comId, value).then((res: any) => {
    // console.log(res);
    templateName.value = res.data.data.map((item) => {
      return {
        label: item.templateName,
        value: item.templateId,
      };
    });
  });
};
const onSelectChange = (Keys: any[]) => {
  selectedRowKeys.value = Keys;
  // console.log(selectedRowKeys.value);
};
</script>
<style scoped>
.ant-form-item {
  margin-bottom: 10px;
}
</style>
